var pos = 0, ctx = null, saveCB, image = [];
$Core.webcam = {
    aParams: {
        width: 320,
        height: 240,
        mode: "callback",
        swffile: "./jscam_canvas_only.swf",
        onTick: function() {
            console.log('onTick');
        },
        onSave: function() {
            console.log('onSave');
        },
        onCapture: function() {
            console.log('onCapture');
        },
        debug: function() {
            console.log('debug');
        },
        onLoad: function() {
            console.log('onLoad');
        }
    },
    capture: function(time) {
        window.capture(time);
    },
    upload: function(url, params) {
        var canvas = document.createElement("canvas");
        canvas.setAttribute('width', 320);
        canvas.setAttribute('height', 240);

        if (canvas.toDataURL) {

            ctx = canvas.getContext("2d");

            image = ctx.getImageData(0, 0, 320, 240);

            saveCB = function(data) {

                var col = data.split(";");
                var img = image;

                for (var i = 0; i < 320; i++) {
                    var tmp = parseInt(col[i]);
                    img.data[pos + 0] = (tmp >> 16) & 0xff;
                    img.data[pos + 1] = (tmp >> 8) & 0xff;
                    img.data[pos + 2] = tmp & 0xff;
                    img.data[pos + 3] = 0xff;
                    pos += 4;
                }

                if (pos >= 4 * 320 * 240) {
                    ctx.putImageData(img, 0, 0);
                    $.post(url, $.extend({type: "data", image: canvas.toDataURL("image/png")}, params));
                    pos = 0;
                }
            };

        } else {

            saveCB = function(data) {
                image.push(data);

                pos += 4 * 320;

                if (pos >= 4 * 320 * 240) {
                    $.post(url, $.extend({type: "pixel", image: image.join('|')}, params));
                    pos = 0;
                }
            };
        }
    },
    load: function(aParams) {
        $.extend(this.aParams, aParams);
    }
}